<?php


namespace app\api\controller\v1;

use app\common\controller\Api;
use think\Db;

/**
 * 场馆接口
 */
class Gymnasium extends Api
{

    protected $noNeedLogin = ['index'];
    protected $noNeedRight = '*';
    protected static $type = [
        1 => '健身馆',
        2 => '瑜伽馆',
        3 => '游泳馆',
        4 => '拳击馆',
        5 => '普拉提馆',
        6 => '私教工作室',
    ];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 场馆列表、详情：传入主键会返回单条信息，此时替他参数无效
     * @ApiMethod (GET)
     * @param string $id 主键：id
     * @param int $type 类型:1=健身房,2=瑜伽,3=游泳馆,4=拳击,5=普拉提
     * @param float $longitude 经度
     * @param float $latitude 纬度
     */
    public function index()
    {
        if ($this->request->isGet()) {

            $id        = input('id');
            $longitude = input('longitude');
            $latitude  = input('latitude');
            $type      = input('type');
            $name      = input('name');

            if (!$id && !$longitude && !$latitude && !$type && !$name) {
                $this->error('必传一个参数');
            }
            $join = [
                0 => '未选择',
                1 => '参与',
                2 => '不参与',
            ];
            if ($id) {
                $result = Db::name('gymnasium')
                    ->where(['id' => $id])
                    ->field('area,is_activity,video,type,name,logo_image,images,phone,share_images,address,longitude,latitude,business_hours,content_,status,likes,is_join,collections')
                    ->find();

                if ($result) {
                    $result['status'] != 1 && $this->error('获取失败,场馆已被禁用');
                    unset($result['status']);
                    $result['logo_image']   = self::patch_cdn($result['logo_image']);
                    $result['images']       = self::patch_cdn($result['images']);
                    $result['share_images'] = self::patch_cdn($result['share_images']);
                    $result['video']        = self::patch_cdn($result['video']);
                    $result['type_text']    = self::$type[$result['type']];
                    $result['is_join_text'] = $join[$result['is_join']];
                    $result['is_like']      = false;
                    $result['is_fabulous']  = false;

                    // 用户登录了才会判断 是否收藏了该场馆
                    if ($this->auth->isLogin()) {
                        $find = Db::name('user_like')->where(['user_id' => $this->auth->id, 'gymnasium_id' => $id])->find();
                        if ($find) {
                            $result['is_like'] = true;
                        }
                    }

                    // 用户登录了才会判断 是否收点赞了该场馆
                    if ($this->auth->isLogin()) {
                        $find = Db::name('user_fabulous')->where(['user_id' => $this->auth->id, 'gymnasium_id' => $id])->find();
                        if ($find) {
                            $result['is_fabulous'] = true;
                        }
                    }

                    // 查询评价信息
                    $result['evaluate'] = Db::name('user_evaluate_gymnasium')
                        ->alias('evaluate')
                        ->join('user user', 'user.id = evaluate.user_id')
                        ->field('evaluate.*,user.avatar')
                        ->where(['gymnasium_id' => $id])
                        ->order('id', 'desc')
//                        ->limit(5)
                        ->select();

                    foreach ($result['evaluate'] as &$item) {
                        $item['createtime'] = date('Y-m-d', $item['createtime']);
                    }

                    $this->success('获取成功', $result);
                } else {
                    $this->error('获取失败,场馆信息不存在');
                }

            } else {
                $where = ['gymnasium.status' => 1];
                if ($type) $where['gymnasium.type'] = $type;
                if ($name) $where['gymnasium.name'] = ['like', $name . '%'];

                $distance = "(6378.138 * 2 * asin(sqrt(pow(sin((gymnasium.latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(gymnasium.latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((gymnasium.longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000)";

                $result = Db::name('gymnasium')
                    ->alias('gymnasium')
                    ->where($where)
                    ->where($distance . '< ' . 1000000000)
                    ->field("gymnasium.id,gymnasium.area,gymnasium.is_activity,gymnasium.name,gymnasium.type,gymnasium.logo_image,gymnasium.thumb_image,$distance as distance,gymnasium.latitude,gymnasium.longitude,gymnasium.address,gymnasium.likes,gymnasium.is_join,gymnasium.collections")
                    ->order('distance', 'asc')
                    ->paginate(null, false, $this->paginate)
                    ->each(function ($item) use ($join) {
                        $item['logo_image']   = self::patch_cdn($item['logo_image']);
                        $item['thumb_image']  = self::patch_cdn($item['thumb_image']);
                        $item['type_text']    = self::$type[$item['type']];
                        $item['distance']     = round(($item['distance'] / 1000), 2);
                        $item['is_join_text'] = $join[$item['is_join']];
                        return $item;
                    });
            }

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 场馆入驻
     * @ApiMethod (POST)
     * @param int $type 类型:1=健身,2=瑜伽,3=游泳馆,4=拳击,5=普拉提
     * @param string $name 名称 max:20|min:4
     * @param string $logo_image logo
     * @param string $phone 联系电话
     * @param string $address 地址 max:150
     * @param float $longitude 经度
     * @param float $latitude 纬度
     * @param string $business_hours 营业时间
     * @param string $license_image 营业执照
     * @param string $card_up_image 身份证正面
     * @param string $card_down_image 身份证反面
     */
    public function create()
    {
        if ($this->request->isPost()) {

            $data = [
                'type'            => input('type'),
                'user_id'         => $this->auth->id,
                'name'            => input('name'),
                'logo_image'      => input('logo_image'),
                'phone'           => input('phone'),
                'address'         => input('address'),
                'longitude'       => input('longitude'),
                'latitude'        => input('latitude'),
                'business_hours'  => input('business_hours'),
                'license_image'   => input('license_image'),
                'card_up_image'   => input('card_up_image', ''),
                'card_down_image' => input('card_down_image', ''),
                'createtime'      => time(),
                'updatetime'      => time(),
            ];

            $rule = [
                'type'           => 'require|between:1,6',
                'user_id'        => 'unique:gymnasium',
                'name'           => 'require|max:20|min:4|unique:gymnasium',
                'logo_image'     => 'require',
//                'phone'          => 'require|length:11|unique:gymnasium',
                'phone'          => 'require|unique:gymnasium',
                'address'        => 'require|max:150',
                'longitude'      => 'require',
                'latitude'       => 'require',
                'business_hours' => 'require',
                'license_image'  => 'require',
//                'card_up_image'   => 'require',
//                'card_down_image' => 'require',
            ];

            $msg = [
                'type.require'           => '场馆类型必填',
                'type.between'           => '错误的场馆类型',
                'user_id.unique'         => '你已经提交过审核',
                'name.require'           => '场馆名称必填',
                'name.max'               => '场馆名称最多20个字符',
                'name.min'               => '场馆名称最少4个字符',
                'name.unique'            => '场馆名称已被占用',
                'logo_image.require'     => '请上传场馆logo',
                'phone.require'          => '请填写手机号',
//                'phone.length'           => '手机号长度不正确',
                'phone.unique'           => '手机号已被占用',
                'address.require'        => '请填写场馆地址',
                'address.max'            => '场馆地址最多150个字符',
                'longitude.require'      => '请选择经纬度',
                'latitude.require'       => '请选择经纬度',
                'business_hours.require' => '请选择营业时间',
                'license_image.require'  => '请上传营业执照',
//                'card_up_image.require'   => '请上传法人身份证正面',
//                'card_down_image.require' => '请上传法人身份证反面',
            ];

            $validate = $this->validate($data, $rule, $msg);

            if (true === $validate) {
                Db::startTrans();
                try {
                    Db::name('gymnasium')->insert($data);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $this->success('提交成功，审核时间不超过48小时，审核通过后客服将与您取得联系');
            } else {
                $this->error($validate);
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 场馆点赞
     * @ApiMethod (GET)
     * @param int $id 场馆主键：id
     */
    public function likes()
    {
        if ($this->request->isGet()) {

            $id = input('id');

            !$id && $this->error('请传入场馆主键');

            $find = Db::name('user_fabulous')->where(['user_id' => $this->auth->id, 'gymnasium_id' => $id, 'type' => 1])->find();
            if ($find) {
                $operate = Db::name('user_fabulous')->delete(['id' => $find['id']]);
                if ($operate > 0) {
                    Db::name('gymnasium')->where(['id' => $id])->setDec('likes');
                    $this->success('取消点赞');
                }
            } else {
                $operate = Db::name('user_fabulous')->insert([
                    'user_id'      => $this->auth->id,
                    'gymnasium_id' => $id,
                    'type'         => 1,
                    'createtime'   => time()
                ]);
                if ($operate) {
                    Db::name('gymnasium')->where(['id' => $id])->setInc('likes');
                    $this->success('点赞成功');
                }
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 用户绑定场馆
     * @ApiMethod (POST)
     * @param int $user_id 用户主键：user_id
     * @param int $gymnasium_id 场馆主键：gymnasium_id
     */
    public function verification()
    {
        if ($this->request->isPost()) {
            $gymnasium_id = input('gymnasium_id');
            $user_id      = input('user_id');

            !$gymnasium_id && $this->error('请传入场馆主键');
            !$user_id && $this->error('请传入用户主键');

            // 验证场馆
            $gymnasium = Db::name('gymnasium')->where(['id' => $gymnasium_id])->field('percentage,status')->find();
            if ($gymnasium) {
                $gymnasium['status'] != 1 && $this->error('场馆被禁用');
            } else {
                $this->error('无效的场馆信息');
            }

            // 核销
            $find = Db::name('user_gymnasium')->where(['user_id' => $user_id, 'gymnasium_id' => $gymnasium_id])->find();
            if ($find) {
                $this->error('核销失败，该用户已核销过');
            } else {
                $result = Db::name('user_gymnasium')->insert(['user_id' => $user_id, 'gymnasium_id' => $gymnasium_id]);
                if (!$result) {
                    $this->success('核销失败');
                }
            }
            $this->success('核销成功');
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 用户评价场馆
     * @ApiMethod (POST)
     * @param int $gymnasium_id 场馆主键：gymnasium_id
     * @param string $evaluate 评价内容
     * @param int $values 评分
     */
    public function evaluate()
    {
        if ($this->request->isPost()) {
            $gymnasium_id = input('gymnasium_id');
            $evaluate     = input('evaluate');
            $values       = input('values');

            !$gymnasium_id && $this->error('请传入场馆主键');
            !$evaluate && $this->error('请传入评价内容');
            !$values && $this->error('请传入评分');

            // 验证场馆
            $gymnasium = Db::name('gymnasium')->where(['id' => $gymnasium_id])->field('percentage,status')->find();
            if ($gymnasium) {
                $gymnasium['status'] != 1 && $this->error('场馆被禁用');
            } else {
                $this->error('无效的场馆信息');
            }

            $result = Db::name('user_evaluate_gymnasium')
                ->insert([
                    'gymnasium_id' => $gymnasium_id,
                    'user_id'      => $this->auth->id,
                    'evaluate'     => $evaluate,
                    'values'       => $values,
                    'createtime'   => time(),
                ]);

            if ($result) {
                $this->success('评价成功');
            } else {
                $this->error('评价成功');
            }

        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 场馆优惠列表
     * @ApiMethod (GET)
     * @param string $type 优惠类型: sanri youhui
     * @param float $longitude 经度
     * @param float $latitude 纬度
     */
    public function getActivityDiscount()
    {
        if ($this->request->isGet()) {

            $longitude = input('longitude');
            $latitude  = input('latitude');
            $type      = input('type');

            $where = ['gymnasium.status' => 1];
            $type == 'sanri' ? $where['is_join'] = 1 : $where['is_activity'] = 1;

            $distance = "(6378.138 * 2 * asin(sqrt(pow(sin((gymnasium.latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(gymnasium.latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((gymnasium.longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000)";

            $result = Db::name('gymnasium')
                ->alias('gymnasium')
                ->where($where)
                ->where($distance . '< ' . 1000000000)
                ->field("gymnasium.id,gymnasium.area,gymnasium.is_activity,gymnasium.name,gymnasium.type,gymnasium.logo_image,gymnasium.thumb_image,$distance as distance,gymnasium.latitude,gymnasium.longitude,gymnasium.address,gymnasium.likes,gymnasium.is_join,gymnasium.collections")
                ->order('distance', 'asc')
                ->paginate(null, false, $this->paginate)
                ->each(function ($item) {
                    $item['logo_image']  = self::patch_cdn($item['logo_image']);
                    $item['type_text']   = self::$type[$item['type']];
                    $item['distance']    = round(($item['distance'] / 1000), 2);
                    return $item;
                });

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }
}
